#include "RTC.h"

void RTC_First_Config()
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP,ENABLE);
	PWR_BackupAccessCmd(ENABLE);
	BKP_DeInit();
	RCC_LSEConfig(RCC_LSE_ON);
	while(RCC_GetFlagStatus(RCC_FLAG_LSERDY)==RESET);
	RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
	RCC_RTCCLKCmd(ENABLE);
	RTC_WaitForSynchro();
	RTC_WaitForLastTask();
	RTC_SetPrescaler(32767);
	RTC_WaitForLastTask();
}

void RTC_Config()
{
		if (BKP_ReadBackupRegister(BKP_DR1)!=0xA5A5)		//读取后备寄存器上的特定数据
	{
		RTC_First_Config();								//如果这个数据没读取到，那说明没有进行第一次初始化
		BKP_WriteBackupRegister(BKP_DR1,0xA5A5);		//这下你知道为什么特定数据是0xA5A5
	}
	else
		if (RCC_GetFlagStatus(RCC_FLAG_PORRST))
		{
			//上电复位要执行的程序往里边写
		}
		else if (RCC_GetFlagStatus(RCC_FLAG_PINRST))
		{
			//外部RST引脚复位写这里
		}
	RCC_ClearFlag();
	
	//虽然RTC不需要重新配置，但RTC的时钟还是要启动的
	RCC_RTCCLKCmd(ENABLE);
	RTC_WaitForSynchro();								//每次启动RTC时钟都要等他和APB1时钟同步
}	
u8 IsLeapYear(u16 year)
{
	if (year%4==0)
	{
		if (year%100==0)
		{
			if (year%400==0)
			{
			return 1;
			}
			else return 0;
		}
		else return 1;
	}
	else return 0;
}

u8 RTC_Set(u16 year,u8 mon,u8 day,u8 hour,u8 min,u8 sec)
{
	u16 t;
	u32 seccount=0;
	if (year < 2000|year > 2099)
	return 1;											//限定时间范围为2000年到2099年
	for (t = 1970;t<year;t++)
	{
		if (IsLeapYear(t))
		seccount+=31622400;
		else seccount+=31536000;
	}
	mon-=1;
	for (t=0;t<mon;t++)
	{
		seccount+=(u32)mon_table[t]*86400;
		if (IsLeapYear(year)&&t==1)
		{
		seccount+=86400;
		}
	}
	seccount+=(u32)(day-1)*86400;
	seccount+=(u32)hour*3600;
	seccount+=(u32)min*60;
	seccount+=sec;
	RTC_First_Config();
	BKP_WriteBackupRegister(BKP_DR1,0xA5A5);
	RTC_SetCounter(seccount);
	RTC_WaitForLastTask();
	return 0;
}

u8 RTC_Get(void)
{
	static u16 dayCount = 0;
	u32 timeCount = 0;
	u32 temp = 0;
	u16 temp1 = 0;
	timeCount = RTC_GetCounter();											//获取RTC计数器的值
	temp = timeCount/86400;												//默认日期一定在2000年后边，不考虑temp=0的情况
	if (dayCount!=temp)
	{
		dayCount=temp;
	}
	temp1=1970;
	while (temp>=365)
	{
		if (IsLeapYear(temp1))
		{
			if (temp>=366)
			{
				temp-=366;
			}
			else temp -=365;
			temp1++;
		}
	}
	readYear = temp1;
	temp1 = 0;
	while (temp>=28)
	{
		if (IsLeapYear(readYear)&&temp1==1)
		{
			if (temp >= 29)
			{
				temp -= 29;
				temp1++;
				continue;
			}
			else
			{
				readMonth = temp1 + 1;
			readDay = temp;
			break;
			}
		}
		if (temp >= mon_table[temp1])
		{
			temp -= mon_table[temp1];
			temp1++;
		}
		else 
		{
			readMonth = temp1 + 1;
			readDay = temp;
			break;
		}
	}
	temp = timeCount%86400;
	readHour = temp/3600;
	readMinute = (temp%3600)/60;
	readSecond = (temp%3600)%60;
	readWeek = RTC_Get_Week(readYear,readMonth,readDay);
}

u16 RTC_Get_Week(u16 year,u8 month,u8 day)
{
	u16 temp2;
	u8 yearH,yearL;
	yearH = year/100;
	yearL = year%100;
	if (yearH > 19)
	{
		yearL+=100;
	}
	temp2=yearL+yearL/4;
	temp2 = temp2%7;
	temp2=temp2+day+table_week[month-1];
	if (yearL%4==0&&month<3)
	{
	temp2--;
	}
	return temp2%7;
}